//
//  PersonalPerformanceViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/5/29.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "PersonalPerformanceViewController.h"

#import "PersonalDataModel.h"
#import "PersonalModel.h"

#import "PersonalTableViewCell.h"



@interface PersonalPerformanceViewController ()<UITableViewDataSource,UITableViewDelegate,sendSelectecdIndexDelegate>
{
    UILabel * _scoreLabel;//本月积分：
    /**本月积分*/
    UILabel * _scoreContentsLabel;
    
    UILabel * _allScoreLabel;//累计积分
    /**累计积分*/
    UILabel * _allScoreContentsLabel;
    
    NSInteger _comboxSelectedIndex;
    

    BOOL _needRefresh;
    
}

@property (nonatomic, strong) NSMutableArray * dataSource;

@property (nonatomic, strong) NSMutableArray * allScore;

@property (nonatomic, strong) UITableView * personalTableView;

@property (nonatomic, assign) NSInteger pageIndex;

@end

@implementation PersonalPerformanceViewController


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _allScore = [NSMutableArray array];
        _dataSource = [NSMutableArray array];
        _pageIndex = 1;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self requestForData];
    [self requestForHeaderData];
    [self creatTableView];
    [self creatComboBox];

}

//刷新
-(void)refresh
{
//    [_refreshHeader beginRefreshing];
}


#pragma mark ------网络请求数据-----------------

- (void)requestForData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    User *user = [User sharedUser];
    NSDictionary *parameters = @{@"id":user.employee_id,@"pagesize":@"10",@"pageindex":[NSString stringWithFormat:@"%ld",(long)_pageIndex],@"time":[NSString stringWithFormat:@"%ld",(long)_comboxSelectedIndex]};
    NSLog(@"=========>>>>>>>>>>>%@",parameters);
    [manager GetWithParameters:parameters method:@"get.manager.score" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
//        NSLog(@"个人业绩的dictonary :%@",[dictionary description]);
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1 && [[dictionary objectForKey:@"total"]intValue] > 0)
        {
            if (_needRefresh) {
                [SVProgressHUD showSuccessWithStatus:@"请求数据中"];
                [_dataSource removeAllObjects];
                }
            
            
            
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                PersonalDataModel *personalDataModel = [[PersonalDataModel alloc]init];
                [personalDataModel setValuesForKeysWithDictionary:dataDic];
                [_dataSource addObject:personalDataModel];
                
            }
            
            [_personalTableView reloadData];
            
            if ([dictionary[@"total"] integerValue] < 10) {
                
                //[_personalTableView.footer resetNoMoreData];
                
                [_personalTableView.footer endRefreshing];
                [_personalTableView.header endRefreshing];
                [_personalTableView.footer noticeNoMoreData];
                return ;
            }
            
            [_personalTableView.footer endRefreshing];
            [_personalTableView.header endRefreshing];
           
            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"暂无数据"];
            [_personalTableView reloadData];
            [_personalTableView.footer endRefreshing];
            [_personalTableView.header endRefreshing];
            [_personalTableView.footer noticeNoMoreData];
        }
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        [_personalTableView.footer endRefreshing];
        [_personalTableView.header endRefreshing];
    }];
    
}

- (void)requestForHeaderData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"id":user.employee_id};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.manager.score" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"个人业绩总业绩dictonary :%@",[dictionary description]);
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                PersonalModel * personalModel = [[PersonalModel alloc]init];
                [personalModel setValuesForKeysWithDictionary:dataDic];
            
                 [_allScore addObject:personalModel];
                
            }
            
            [_personalTableView reloadData];
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}




- (void)creatComboBox
{
    NSArray *comboBoxDatasource = [[NSArray alloc] initWithObjects:@"全部", @"本周", @"最近一月", @"本月", @"最近半年", @"最近一年", nil];
    
    _comboBox = [[ComboBoxView alloc] initWithFrame:CGRectMake(SCREEN_W - SCREEN_W/4-10, 72, SCREEN_W/4, 200)];
    _comboBox.comboBoxDatasource = comboBoxDatasource;
    _comboBox.backgroundColor = [UIColor clearColor];
    _comboBox.delegate = self;
    [_comboBox setContent:[comboBoxDatasource objectAtIndex:0]];
    //[_comboBox.com];
    [self.view addSubview:_comboBox];
}
#pragma mark-sendSelectecdIndexDelegate
- (void)sendSelectedIndex:(NSInteger)selectedIndex{
    [_dataSource removeAllObjects];
    _comboxSelectedIndex = selectedIndex;
    _pageIndex = 1;
    [self requestForData];
}
- (void)creatTableView
{
    _personalTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) style:UITableViewStylePlain];
    
    _personalTableView.delegate = self;
    _personalTableView.dataSource = self;
    _personalTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
     [self.view addSubview:_personalTableView];
    
//    [_personalTableView registerClass:[PersonalTableViewCell class] forCellReuseIdentifier:@"PersonalCell"];
    
    UINib * nib = [UINib nibWithNibName:@"PersonalTableViewCell" bundle:nil];
    
    [_personalTableView registerNib:nib forCellReuseIdentifier:@"PersonalCell"];

    _personalTableView.tableHeaderView = [[UIView alloc] init];
    
    __weak typeof(self) weakSelf = self;
    [_personalTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    [_personalTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];

    
}
- (void)headerRefresh{
    _needRefresh = YES;
    _pageIndex = 1;
    [self requestForData];
}
- (void)footerRefresh{
    _needRefresh = NO;
    _pageIndex ++;
    [self requestForData];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataSource count];
    //return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"PersonalCell";
   
    PersonalTableViewCell * cell = (PersonalTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[PersonalTableViewCell alloc]init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if(_dataSource)
    {
        [cell fillCellWithModel:_dataSource[indexPath.row]];
    }
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}


//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//}
//
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
//
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 44)];
    [contentView setBackgroundColor:[UIColor colorWithRed:0.88 green:0.88 blue:0.88 alpha:1.0]];
    
    _scoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 60, contentView.frame.size.height)];
    
    _scoreContentsLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_scoreLabel.frame), 0,SCREEN_W/6, contentView.frame.size.height)];

    
    _allScoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_scoreContentsLabel.frame), 0, 60, contentView.frame.size.height)];
    
    _allScoreContentsLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_allScoreLabel.frame), 0, SCREEN_W/6, contentView.frame.size.height)];
    
    _scoreLabel.text = @"本月积分:";
    _allScoreLabel.text = @"累计积分:";
    _scoreContentsLabel.text = @"暂无数据";
    _allScoreContentsLabel.text = @"暂无数据";
    
    if (_allScore.count == 1) {
        PersonalModel * personalModel = _allScore[0];
        _scoreContentsLabel.text = personalModel.month_score;
        _allScoreContentsLabel.text = personalModel.total_score;
    }
    

    
//    _scoreContentsLabel.text = @"5000";
//    _allScoreContentsLabel.text = @"1500";
    
    _scoreLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
    _allScoreLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
    _scoreContentsLabel.font = [UIFont fontWithName:@"Arial" size:12];
    _allScoreContentsLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
    
    _scoreContentsLabel.textColor = [UIColor redColor];
    _allScoreContentsLabel.textColor = [UIColor redColor];
    
    
    
   
    
    [contentView addSubview:_scoreLabel];
    [contentView addSubview:_scoreContentsLabel];
    [contentView addSubview:_allScoreLabel];
    [contentView addSubview:_allScoreContentsLabel];
    
    return contentView;
}


//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    
//}



@end
